import { MeshRenderer } from 'cc';
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PageWorldBg')
export class PageWorldBg extends Component {
    @property(Node)
    bg1: Node = null;

    @property(Node)
    bg2: Node = null;

    private _movingSpeed: number = 2;
    private _movingRange: number = 20;

    start() {
        // 在xz平面上移动
        this.bg1.setPosition(this.bg1.position.x, 0, 0);
        this._movingRange = this.bg1.getComponent(MeshRenderer).model.worldBounds.halfExtents.z * 2;
        this.bg2.setPosition(this.bg2.position.x, 0, this._movingRange);
    }

    update(deltaTime: number) {
        this.moveBg(deltaTime);
    }

    moveBg(deltaTime: number) {
        // y轴方向滚动背景
        this.bg1.setPosition(this.bg1.position.x, 0, this.bg1.position.z + this._movingSpeed * deltaTime);
        this.bg2.setPosition(this.bg2.position.x, 0, this.bg2.position.z + this._movingSpeed * deltaTime);
        if (this.bg1.position.z >= this._movingRange) {
            this.bg1.setPosition(this.bg1.position.x, 0, this.bg2.position.z - this._movingRange);
        } else if (this.bg2.position.z >= this._movingRange) {
            this.bg2.setPosition(this.bg2.position.x, 0, this.bg1.position.z - this._movingRange);
        }
    }
}


